<template>
    <div>
        <el-card class="box-card">
            <h2>起草合同</h2>
            <el-form :model="contractForm" :rules="rules" ref="contractForm" label-width="120px">
                <el-form-item label="合同名称：" prop="name">
                    <el-input v-model="contractForm.name"></el-input>
                </el-form-item>
                <el-form-item label="客户：" prop="customer">
                    <el-select v-model="contractForm.customer" placeholder="请选择客户">
                        <el-option
                                v-for="customer in customers"
                                :key="customer"
                                :label="customer"
                                :value="customer"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="开始时间：" prop="beginTime">
                    <el-date-picker
                            v-model="contractForm.beginTime"
                            type="date"
                            placeholder="选择开始日期"
                            :picker-options="beginDatePickerOptions"
                    ></el-date-picker>
                </el-form-item>
                <el-form-item label="结束时间：" prop="endTime">
                    <el-date-picker
                            v-model="contractForm.endTime"
                            type="date"
                            placeholder="选择结束日期"
                            :picker-options="endDatePickerOptions"
                    ></el-date-picker>
                </el-form-item>
                <el-form-item label="合同内容：" prop="content">
                    <el-input v-model="contractForm.content" type="textarea" :rows="10"></el-input>
                </el-form-item>
                <el-form-item label="合同附件：">
                    <el-upload
                            action="/api/contract/upload"
                            list-type="text"
                            :on-success="handleUploadSuccess"
                            :on-error="handleUploadError"
                    >
                        <el-button slot="trigger" type="primary">上传附件</el-button>
                        <div slot="tip" class="el-upload__tip">上传合同附件，单个文件最大2MB</div>
                    </el-upload>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="submitForm">提交</el-button>
                    <el-button @click="resetForm">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>
    </div>
</template>

<script>
export default {
    data() {
        return {
            contractForm: {
                name: '',
                customer: '',
                beginTime: '',
                endTime: '',
                content: '',
                userName: '',
                attachments: []
            },
            customers: [], // Array to hold customer data
            rules: {
                name: [{ required: true, message: '请输入合同名称', trigger: 'blur' }],
                customer: [{ required: true, message: '请选择客户', trigger: 'change' }],
                beginTime: [
                    { required: true, message: '请选择开始时间', trigger: 'change' },
                    { validator: this.validateBeginTime, trigger: 'change' }
                ],
                endTime: [
                    { required: true, message: '请选择结束时间', trigger: 'change' },
                    { validator: this.validateEndTime, trigger: 'change' }
                ],
                content: [{ required: true, message: '请输入合同内容', trigger: 'blur' }]
            }
        };
    },
    computed: {
        beginDatePickerOptions() {
            return {
                disabledDate: time => time.getTime() < Date.now() - 86400000
            };
        },
        endDatePickerOptions() {
            return {
                disabledDate: time => this.contractForm.beginTime
                    ? time.getTime() < new Date(this.contractForm.beginTime).getTime()
                    : false
            };
        }
    },
    methods: {
        handleUploadSuccess(response, file) {
            this.contractForm.attachments.push(response.url);
            this.$message.success(`${file.name} 上传成功`);
        },
        handleUploadError(err, file) {
            this.$message.error(`${file.name} 上传失败`);
        },
        submitForm() {
            this.contractForm.userName = this.getCurrentUserName();
            this.$refs.contractForm.validate(valid => {
                if (valid) {
                    this.axios.post('/api/contract/draft', this.contractForm)
                        .then(() => {
                            this.$message.success('合同起草成功');
                            this.resetForm();
                        })
                        .catch(error => {
                            console.error('Error creating contract:', error);
                            this.$message.error('合同起草失败');
                        });
                } else {
                    this.$message.error('请完善表单信息');
                }
            });
        },
        getCurrentUserName() {
            return '当前用户'; // Replace with actual method to get current user
        },
        resetForm() {
            this.$refs.contractForm.resetFields();
            this.contractForm.attachments = [];
        },
        validateBeginTime(rule, value, callback) {
            if (value && new Date(value).getTime() < Date.now() - 86400000) {
                callback(new Error('开始时间不能早于今天'));
            } else {
                callback();
            }
        },
        validateEndTime(rule, value, callback) {
            if (value && new Date(value).getTime() < new Date(this.contractForm.beginTime).getTime()) {
                callback(new Error('结束时间不能早于开始时间'));
            } else {
                callback();
            }
        },
        fetchCustomers() {
            this.axios.get('/api/customer/get')
                .then(response => {
                    this.customers = response.data.data.map(customer => customer.name);
                })
                .catch(error => {
                    console.error('Error fetching customers:', error);
                    this.$message.error('获取客户列表失败');
                });
        }
    },
    created() {
        this.fetchCustomers(); // Fetch customers when the component is created
    }
};
</script>

<style scoped>
.box-card {
    margin: auto;
    width: 600px;
}
.el-form-item {
    margin-bottom: 20px;
}
</style>
